# -*- coding: utf8 -*-

__author__ = "Sergey Dryabzhinsky"

__doc__ = """
Обработка изображения

@author: Sergey Dryabzhinsky
"""

from logger import get_file_logger
from multiprocessing import current_process
from threading import current_thread
import numpy as np
from scipy.misc import imread, imresize
from scipy.signal.signaltools import correlate2d as c2d

class iNumpy( object ):
    filename = None

    img = None

    log = None

    def get_logger(self):
        if self.log is None:
            self.log = get_file_logger(
                self.__class__.__name__ + "[%s-%s]" % (current_process( ).pid, current_thread( ).getName( )) )
        return self.log

    def is_image(self, filename):
        is_img = False
        try:
            self.load( filename )
            w, h = self.img.shape[:2]
            if w and h:
                is_img = True
        except Exception as e:
            self.get_logger().error("is_image: %r, filename=%r" % (e, filename,))
            pass
        self.close()
        return is_img

    def close(self):
        if self.img is not None:
            self.img = None
            self.filename = None
        return self

    def load(self, filename, flatten=0):
        self.img = imread( filename.encode( 'utf-8' ), flatten=flatten )
        return self.img

    def width(self):
        if self.img is not None:
            return self.img.shape[ 0 ]
        return 0

    def height(self):
        if self.img is not None:
            return self.img.shape[ 1 ]
        return 0

    def process_image(self, mirror = False, parts = 100):
        """
        Process image data and calculate some results

        @return:    calculated data:
                    {
                        "vector" : numpy.array
                    }
        @rtype:     dict
        """

        result = {
            "color": False,
            "mean_gray": 0,
            "vector": None
        }

        img = self.img

        if mirror:
            img = np.fliplr(img)

        w, h = img.shape[:2]

        if w == 0 or h == 0:
            vector = np.array([[0]])
        else:
            new_w = int(w*(1.0 - 0.85))
            new_h = int(h*(1.0 - 0.85))
            img = imresize(img, (new_w, new_h), 'bicubic')
            # normalize per http://en.wikipedia.org/wiki/Cross-correlation

            std = img.std()
            mean = img.mean()
            if std:
                vector = (img - mean) / std
            else:
                vector = img - mean

        result[ "vector" ] = vector
        return result

    def convert_to_linear(self, im1, parts=100):
        line = np.reshape(im1, im1.shape[0]*im1.shape[1])
        line *= 255.0
        zeros = np.zeros((parts,), dtype=line.dtype)
        zeros[:line.shape[0]] = line
        return tuple([int(v) for v in zeros])

    def compare_vectors(self, im1, im2):
        c11 = c2d(im1, im1, mode='same')
        c12 = c2d(im1, im2, mode='same')
        base = c11.max()
        comp = c12.max()
        return comp / base * 100
